<!DOCTYPE html>
<html>
  <head>
    <metacharset="UTF-8"/>
    <metaname="viewport"content="width=device-width, initial-scale=1.0"/>
    <title>WebSocket 发送普通文本示例</title>
    <style>
      .block {
        flex: 1;
      }
    </style>
  </head>
  <body>
    <h3>WebSocket 发送普通文本示例</h3>
    <divstyle="display: flex;">
      <divclass="block">
        <p>即将发送的数据：<button>发送</button></p>
        <textareaid="sendMessage"rows="5"cols="15"></textarea>
      </div>
      <divclass="block">
        <p>接收的数据：</p>
        <textareaid="receivedMessage"rows="5"cols="15"></textarea>
      </div>
    </div>
    <script>
      const sendMsgContainer = document.querySelector("#sendMessage");
      const receivedMsgContainer = document.querySelector("#receivedMessage");
      const socket = new WebSocket("ws://echo.websocket.org");
      // 监听连接成功事件
      socket.addEventListener("open", function (event) {
        console.log("连接成功，可以开始通讯");
      });
      // 监听消息
      socket.addEventListener("message", function (event) {
        console.log("Message from server ", event.data);
        receivedMsgContainer.value = event.data;
      });
      function send() {
        const message = sendMsgContainer.value;
        if (socket.readyState !== WebSocket.OPEN) {
          console.log("连接未建立，还不能发送消息");
          return;
        }
        if (message) socket.send(message);
      }
    </script>
  </body>
</html>